package com.yunshang.ysmall.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.pingplusplus.Pingpp;
import com.pingplusplus.exception.APIConnectionException;
import com.pingplusplus.exception.APIException;
import com.pingplusplus.exception.AuthenticationException;
import com.pingplusplus.exception.ChannelException;
import com.pingplusplus.exception.InvalidRequestException;
import com.pingplusplus.exception.RateLimitException;
import com.pingplusplus.model.Charge;
import com.pingplusplus.model.Event;
import com.pingplusplus.model.PingppObject;
import com.pingplusplus.model.Webhooks;
import com.yunshang.ysmall.mapper.OrderInfoMapper;
import com.yunshang.ysmall.model.CallBackMoneySide;
import com.yunshang.ysmall.model.MbAddrInfo;
import com.yunshang.ysmall.model.OrderInfo;
import com.yunshang.ysmall.model.OrderItemInfo;
import com.yunshang.ysmall.model.ProductImgList;
import com.yunshang.ysmall.model.ProductInfo;
import com.yunshang.ysmall.model.ProductTypeInfo;
import com.yunshang.ysmall.service.MemberService;
import com.yunshang.ysmall.service.OrderService;
import com.yunshang.ysmall.service.ProductService;
import com.yunshang.ysmall.util.Constants;
import com.yunshang.ysmall.util.DateUtils;
import com.yunshang.ysmall.util.HttpClientUtils;
import com.yunshang.ysmall.util.MD5Utils;

import net.coobird.thumbnailator.Thumbnails;

@Controller
@RequestMapping("/order")
public class OrderController {
	//定义一个静态交易码
	private static String bonusCode=null;

	private static Logger logger = LoggerFactory.getLogger(OrderController.class);

	@Resource
	ProductService productService;
	@Resource
	MemberService memberService;
	@Resource
	OrderService orderService;

	public static final String ROOT = "static/upload-dir/";
	
	@RequestMapping("/toorderlist")
	public String toorderlist(OrderInfo orderInfo, Model model) {
		Map params = new HashMap();
		//订单的编号不为空
		if (orderInfo.getOrderId() != null && !"".equals(orderInfo.getOrderId())) {
			params.put("orderId", orderInfo.getOrderId().trim());
		}
		//会员编号不为空
		if (orderInfo.getMemberId() != null && !"".equals(orderInfo.getMemberId())) {
			params.put("memberId", orderInfo.getMemberId().trim());
		}
		params.put("startIndex", 0);
		params.put("pageSize", 10000);
		model.addAttribute("orderList", memberService.getOrderListByParams(params));
		return "/mng/main/order/orderlist";
	}
	
	@RequestMapping("/toorderlist/waithandle")
	public String toorderlistWaithandle(OrderInfo orderInfo, Model model){
		Map<String,Object> params=new HashMap<String,Object>();
		if(orderInfo.getMemberId()!=null&&!orderInfo.getMemberId().equals("")){
			params.put("memberId", orderInfo.getMemberId().trim());
		}
		if(orderInfo.getOrderId()!=null&&!orderInfo.getOrderId().equals("")){
			params.put("orderId", orderInfo.getOrderId().trim());
		}
		//查询状态是已支付但是未发货的数据.订单状态是2物流状态是0
		List<OrderInfo> orderInfoList=memberService.findOrderList(params);
		model.addAttribute("orderInfoLists", orderInfoList);
		return "/mng/main/order/pendingorderlist";
	}

	@RequestMapping("/detail")
	public String edit(String oid, Model model) {
			//根据订单id来查询订单信息
		OrderInfo orderInfo = memberService.getOrderInfoById(oid);
		orderInfo.setOrderTs(
				DateUtils.string2Date(orderInfo.getOrderDate() + orderInfo.getOrderTime(), "yyyyMMddHHmmss"));
		//根据订单id来查询所有的订单详细信息
		List<OrderItemInfo> itemList = memberService.getOrderItemListByOrderId(oid);
		model.addAttribute("itemList", itemList);
		model.addAttribute("orderInfo", orderInfo);
		MbAddrInfo addressInfo = memberService.getAddrById(orderInfo.getAddrId());
		model.addAttribute("addressInfo", addressInfo);
		return "/mng/main/order/detail";
	}

	//后台的订单详细查询
	@RequestMapping("/orderInDetail")
	public String orderInDetail(String orderId,Model model){
		OrderInfo orderInfo=orderService.getOrderInfo(orderId);
		orderInfo.setOrderTs(
				DateUtils.string2Date(orderInfo.getOrderDate() + orderInfo.getOrderTime(), "yyyyMMddHHmmss"));
		MbAddrInfo mbAddrInfo=orderService.getMbAddrInfo(orderInfo.getAddrId());
		model.addAttribute("orderInfo", orderInfo);
		model.addAttribute("mbAddrInfo", mbAddrInfo);
		return "/mng/main/order/orderindetail";
	}
	
	
	//填写物流的单号
	@RequestMapping("/fahuo")
	public String editpro(OrderInfo orderInfo, Model model) {
		memberService.updateOrder(orderInfo);
		return "redirect:/order/toorderlist/waithandle";
	}
	
	@RequestMapping("/notify")
	public void notify(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("UTF8");
			// 获取头部所有信息
			Enumeration headerNames = request.getHeaderNames();
			//判断枚举中是否含有元素
			while (headerNames.hasMoreElements()) {
				//获取下一个元素
				String key = (String) headerNames.nextElement();
				//获取指定请求头的值
				String value = request.getHeader(key);
				System.out.println(key + " " + value);
			}
			// 以浏览器使用的字符编码获得 http body 内容。
			BufferedReader reader = request.getReader();
			StringBuffer buffer = new StringBuffer();
			String string;
			while ((string = reader.readLine()) != null) {
				buffer.append(string);
			}
			reader.close();

			// 解析异步通知数据
			Event event = Webhooks.eventParse(buffer.toString());
			if ("charge.succeeded".equals(event.getType())) {
				response.setStatus(200);
				Object obj = Webhooks.getObject(buffer.toString());
				Charge charge = (Charge) obj;   
				//查找订单信息
				OrderInfo orderInfo =memberService.getOrderInfoById(charge.getOrderNo());
				//去扣款扣积分
				if(memberpay(orderInfo)){
					//设置订单状态为已支付状态。0代表未支付状态
					orderInfo.setOrderStatus(2);
					//保存交易码
					if(bonusCode!=null){
						Map< String, Object> parameters=new HashMap<String, Object>();
						parameters.put("orderId",orderInfo.getOrderId());
						parameters.put("bonusCode", bonusCode);
						memberService.updateBonusCode(parameters);
					}
				}else{
					orderInfo.setOrderStatus(5);
				}
				memberService.updateOrder(orderInfo);
			} else if ("refund.succeeded".equals(event.getType())) {
				response.setStatus(200);
			} else {
				response.setStatus(500);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	 
	//处理钱方支付成功后的回调处理
	@RequestMapping("/notifyformQf")
	public void notifyformQf(@RequestBody CallBackMoneySide cby,HttpServletRequest request){	
	/*
	 * [cby]:[商品名称][流水号]20171120000300020024233924[外部订单号]houhe207e6de6-8f6f-44f7-9ee5-004e36ee7ea2||2017-11-20 12:13:05[通知类型  ]payment[返回支付类型]800207
	 * [请求交易时间]2017-11-20 12:13:05
	 * [订单支付金额]100[交易返回码]0000
	*系统交易时间]2017-11-20 12:13:05[退款标记]
	*0[交易状态码 ]1[子商户号]dWamPhlnpW[币种 ]CNY
	 * 
	 * */	
		logger.info("[cby]:"+"[商品名称]"+cby.getGoods_name()+"[流水号]"+cby.getSyssn()
				+"[外部订单号]"+cby.getOut_trade_no()+"[通知类型  ]"+cby.getNotify_type()+"[返回支付类型]"+cby.getPay_type()+"[请求交易时间]"+cby.getTxdtm()+"[订单支付金额]"+cby.getTxamt()
				+"[交易返回码]"+cby.getRespcd()+"[系统交易时间]"+cby.getSysdtm()+"[退款标记]"+cby.getCancel()+"[交易状态码 ]"+cby.getStatus()+"[子商户号]"+cby.getMchid()+"[币种 ]"+cby.getTxcurrcd()
				+"[suceess]:交易成功");
		OrderInfo orderInfo=orderService.getOrderInfoByOrderId(cby.getOut_trade_no());
		if(cby.getRespcd().equals("0000")&&cby.getStatus().equals("1")){
			//支付成功否则是支付失败.支付成功则扣除积分
			//扣积分，然后更改订单状态
			if(memberpay(orderInfo)){
				//修改订单状态
				orderInfo.setOrderStatus(2);
				//保存交易码
				if(bonusCode!=null){
					Map< String, Object> parameters=new HashMap<String, Object>();
					parameters.put("orderId",orderInfo.getOrderId());
					parameters.put("bonusCode", bonusCode);
					memberService.updateBonusCode(parameters);
				}
				//删除session信息
				request.getSession().removeAttribute("orderInfo");
				memberService.updateOrder(orderInfo);
				logger.info("[order:订单保存并且积分已经扣除]");
			}else{
				orderInfo.setOrderStatus(5);
			}
		}
	}
	
	//扣积分
	private boolean memberpay(OrderInfo orderInfo){
		try{
			String url ="http://www.yssy7.com/scapi.aspx?client_id=YUNSHANG08";
			String key ="ys123456";
			System.out.println(orderInfo.getMemberId()+orderInfo.getTransBonus()+orderInfo.getOrderId());
			//转换的为："{"USER_ALIAS":""orderInfo"","PAY_TYPE":"3","MONEY":""orderInfo.getTransBonus()"","ORDER_NO":"""","PAY_IP":"127.0.0.1"}"
			String param = URLEncoder.encode("{\"USER_ALIAS\":\""+orderInfo.getMemberId()+"\",\"PAY_TYPE\":\"3\",\"MONEY\":\""+orderInfo.getTransBonus()+"\",\"ORDER_NO\":\""+orderInfo.getOrderId()+"\",\"PAY_IP\":\"127.0.0.1\"}","utf-8");
			//获取当前时间，转换为指定的格式
			String ndate = DateUtils.currentDate("HHmmss");
			//对传入的参数进行加密并且全部转换为小写
			String md5 = MD5Utils.MD5("YUNSHANG08"+key+ndate).toLowerCase();
			String requestUrl = url+"&schema_name=GET_USER_ACCOUNT_PAY&parameter="+param+"&ndate="+ndate+"&md5="+md5;
			logger.info("requestUrl:"+requestUrl);
			String result = HttpClientUtils.httpGet(requestUrl);
			//讲结果输入到日志中
			logger.info("result:"+result);
		// {"result":"success","total":1,"data":[{"NAME":"乔江2","DWALLET":"0.74","USER_ALIAS":"AN809702","PASSWORD":"96e79218965eb72c92a549dd5a330112","ISLOGIN":1.0}]};
			//将获取的字符串转换为json对象
			JSONObject jsonObject = JSONObject.parseObject(result);
			//判断这个json对象中是否含有sucess值
			if("success".equals(jsonObject.getString("result"))){
				JSONObject data = jsonObject.getJSONArray("data").getJSONObject(0);
				if ("1".equals(data.getString("ISPAY").split("\\|")[0])) {
					bonusCode=data.getString("ISPAY").split("\\|")[1];//交易流水号
					return true;
				}
			}
			return false;
		}catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		
	}
	
}
